package com.yff.tuan.util;

import org.apache.commons.codec.binary.Base64;

import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import java.util.HashMap;
import java.util.Map;

import javax.crypto.Cipher;
 
/**
 * Created by humf.需要依赖 commons-codec 包 
 */
public class RSAUtil {
    public static final String KEY_ALGORITHM = "RSA";
    public static final String SIGNATURE_ALGORITHM = "MD5withRSA";
 
    private static final String PUBLIC_KEY = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBAKPVFX3xaI3vy8PTmQCoO4n4b+BJJD2FHAn6tDN+A3kL6BV/cwKBFtC9ULSTvP8buw0DZdPDEB+6nPpWIUuxhZs8LRj3Dx6DPaV48eDXVJ5ooXSXQVdSQY2z99NusvhEJ1cwCM3BByi75k6lcYjeukgL9H8XWU2QLhRaF0G3e/wTAgMBAAECgYB59HewLdEnvzZOiqfdfl37wYz+R1QL25dYsmAL6KULKVrVDe9+ELv8HMED+un4eRsPf9UAArdw9wg9rXnRj88k3slPYV2Vri/IFHZMjd/omF0hOhNA9Dkz8bCDUlyeiG34H47l3UJsdhlfOP6V3990I4F78bjA3sDhYFFuhyOpMQJBAPRQiID/m+nOAykk//6i+fzGf0NvM9d/eoQm8I2XXShLr4rJNzSk/m1LDnX9VhznMsNwFXews9iuapoxb+n3QSsCQQCrqxmwzSu7sy27Tdy0i+5g26Mr179/Af0hzX21OSJbpkDVW4S0vD7dNAp5oj7zL6o785AmW8967DUN6IXXj6y5AkEAgnMxv7c718ZBV8nCyoLY+kg+kZIh2zHdCA0GqoOkoSxwaalwybJDi7Xk3clMHpiwOTxyqfr2vH68uuIkwIdeCwJBAKS+HXhzXQ3TRQbkEPLe+tPO08dmU6qiEPdYidPZUaScZsmZ+z+rC7UilQ7nafvc+URxWBvHrdQsTDndtFwK0FkCQQCHiYy2UwF45DnvdKL1sUILiODV/Yvyt5hK7vW/UpoPkgShAPN8PbXPM6GBLZ77tm9wc1rMXrhbuLtLy3AA6CGq";
    private static final String PRIVATE_KEY = "MIICdQIBADANBgkqhkiG9w0BAQEFAASCAl8wggJbAgEAAoGBAIeI5u529xUYg0AUzBRUASMs7xbflmaumNicsJI9GQ4oGI9sW6CEkiAnCnZO/RmO3bSu5/j9DXMEfNMQYn5Zr2VDslqSHEorOOs/hDdayzTnJhrsEtezwMC9nn/sWkF0CD8l3NKh7Eaj4CJNf5T7aOXfg8MzBbfOw5tNOSiZUe1/AgMBAAECgYBuSr654T9yAE+WTxY/mJiQWll5wJrwljY1V1TsvCFufrx1whTSC++pkHuYCPE34iWSih6lZK+UIFu/mf68mRj72+/fJAPgxEiFCHPpoGQeFlaCu98v1sqoCgfsKoAMukDpaWOR1GDk4/OIpcWSG5S6LL1StZ/dYMk0syw8mq+COQJBAMfdMSaNf6P3yXmGlCsZ6mzF+6CwiOUts9S2G3q3fy3Un2/elzGXefRN1mCDGcVVVYiBi+jKp8C82cdRI+AFgTUCQQCtmj+aOunORHFLN0/ETHXRIutSHUIZ0y6andWlLLJWCNOpggGp6T1t2YnWXdqoaxAvueTT0P4R8Mh2XRFeMd5jAkAH1aLcmQVc3xS1v9HFEsH+u5AOj3z+RtlayDyxhcnleQU69GXG2uI78mUp6Vm0Q5ETxcg/OtpykrSSvJqEaJLVAkA6Ze8LVNId3ww1fy/IGuhvJ839W3ZG9bFxtbKO09BR/LonBWLF434Um98wS3YovYs+YsxFLMKrClKE7p3PD/t9AkAR1Mbjdtlc4summhsWKlXPUDcuyb7sHvGRLi/2B94IxxT7Ybr/n8G71j4Gvd8pCiJSHgLnFftMhM67o0S7YN4+";
 
    public static byte[] decryptBASE64(String key) {
        return Base64.decodeBase64(key);
    }
 
    public static String encryptBASE64(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }
 
    /**
     * 用私钥对信息生成数字签名
     *
     * @param data       加密数据
     * @param privateKey 私钥
     * @return
     * @throws Exception
     */
    public static String sign(byte[] data, String privateKey) throws Exception {
        // 解密由base64编码的私钥
        byte[] keyBytes = decryptBASE64(privateKey);
        // 构造PKCS8EncodedKeySpec对象
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取私钥匙对象
        PrivateKey priKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 用私钥对信息生成数字签名
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initSign(priKey);
        signature.update(data);
        return encryptBASE64(signature.sign());
    }
 
    /**
     * 校验数字签名
     *
     * @param data      加密数据
     * @param publicKey 公钥
     * @param sign      数字签名
     * @return 校验成功返回true 失败返回false
     * @throws Exception
     */
    public static boolean verify(byte[] data, String publicKey, String sign)
            throws Exception {
        // 解密由base64编码的公钥
        byte[] keyBytes = decryptBASE64(publicKey);
        // 构造X509EncodedKeySpec对象
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
        // KEY_ALGORITHM 指定的加密算法
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        // 取公钥匙对象
        PublicKey pubKey = keyFactory.generatePublic(keySpec);
        Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
        signature.initVerify(pubKey);
        signature.update(data);
        // 验证签名是否正常
        return signature.verify(decryptBASE64(sign));
    }
 
    public static byte[] decryptByPrivateKey(byte[] data, String key) throws Exception{
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }
 
    /**
     * 解密<br>
     * 用私钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPrivateKey(String data, String key)
            throws Exception {
        return decryptByPrivateKey(decryptBASE64(data),key);
    }
 
    /**
     * 解密<br>
     * 用公钥解密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] decryptByPublicKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据解密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.DECRYPT_MODE, publicKey);
        return cipher.doFinal(data);
    }
 
    /**
     * 加密<br>
     * 用公钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPublicKey(String data, String key)
            throws Exception {
        // 对公钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得公钥
        X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key publicKey = keyFactory.generatePublic(x509KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, publicKey);
        return cipher.doFinal(data.getBytes());
    }
 
    /**
     * 加密<br>
     * 用私钥加密
     *
     * @param data
     * @param key
     * @return
     * @throws Exception
     */
    public static byte[] encryptByPrivateKey(byte[] data, String key)
            throws Exception {
        // 对密钥解密
        byte[] keyBytes = decryptBASE64(key);
        // 取得私钥
        PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
        KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
        Key privateKey = keyFactory.generatePrivate(pkcs8KeySpec);
        // 对数据加密
        Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
        cipher.init(Cipher.ENCRYPT_MODE, privateKey);
        return cipher.doFinal(data);
    }
 
    /**
     * 取得私钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPrivateKey(Map<String, Key> keyMap)
            throws Exception {
        Key key = (Key) keyMap.get(PRIVATE_KEY);
        return encryptBASE64(key.getEncoded());
    }
 
    /**
     * 取得公钥
     *
     * @param keyMap
     * @return
     * @throws Exception
     */
    public static String getPublicKey(Map<String, Key> keyMap)
            throws Exception {
        Key key = keyMap.get(PUBLIC_KEY);
        return encryptBASE64(key.getEncoded());
    }
 
    /**
     * 初始化密钥
     *
     * @return
     * @throws Exception
     */
    public static Map<String, Key> initKey() throws Exception {
        KeyPairGenerator keyPairGen = KeyPairGenerator
                .getInstance(KEY_ALGORITHM);
        keyPairGen.initialize(1024);
        KeyPair keyPair = keyPairGen.generateKeyPair();
        Map<String, Key> keyMap = new HashMap<String, Key>(2);
        keyMap.put(PUBLIC_KEY, keyPair.getPublic());// 公钥
        keyMap.put(PRIVATE_KEY, keyPair.getPrivate());// 私钥
        return keyMap;
    }
    
    public static String encrypt(String value) throws Exception{
    	Map<String, Key> keyMap = initKey();
    	byte[] encryptByPrivateKey = encryptByPrivateKey(value.getBytes(),getPrivateKey(keyMap));
    	return new String(encryptByPrivateKey,"UTF-8");
    }
    
    public static String decrypt(String value) throws Exception{
    	Map<String, Key> keyMap = initKey();
    	byte[] decryptByPublicKey = decryptByPublicKey(value.getBytes(),getPublicKey(keyMap));
    	return new String(decryptByPublicKey,"UTF-8");
    }
    
    public static void main(String[] args) throws Exception {
        Map<String, Key> keyMap = initKey();
        String publicKey = getPublicKey(keyMap);
        String privateKey = getPrivateKey(keyMap);
        
        /*System.out.println(keyMap);
        System.out.println("-----------------------------------");
        System.out.println(publicKey);
        System.out.println("-----------------------------------");
        System.out.println(privateKey);
        System.out.println("-----------------------------------");*/
        byte[] encryptByPrivateKey = encryptByPrivateKey("piadd".getBytes(),privateKey);
        byte[] encryptByPublicKey = encryptByPublicKey("piadd",publicKey);
        System.out.println(new String(encryptByPrivateKey,StandardCharsets.UTF_8));
        System.out.println("-----------------------------------");
        System.out.println(new String(encryptByPublicKey,StandardCharsets.UTF_8));
        System.out.println("-----------------------------------");
        String sign = sign(encryptByPrivateKey,privateKey);
        System.out.println(sign);
        System.out.println("-----------------------------------");
        boolean verify = verify(encryptByPrivateKey,publicKey,sign);
        System.out.println(verify);
        System.out.println("-----------------------------------");
        byte[] decryptByPublicKey = decryptByPublicKey(encryptByPrivateKey,publicKey);
        byte[] decryptByPrivateKey = decryptByPrivateKey(encryptByPublicKey,privateKey);
        System.out.println(new String(decryptByPublicKey));
        System.out.println("-----------------------------------");
        System.out.println(new String(decryptByPrivateKey));
    	
    	System.out.println(encrypt("123456").toString());
    	/*System.out.println(decrypt("123456"));*/
        
    }
}